package net.imagine.provider.skyline;

import java.io.File;
import java.io.IOException;
import java.util.List;

import net.imagine.core.FileKeyGenerator;
import net.imagine.core.ImageInfo;
import net.imagine.core.ResultState;
import net.imagine.core.crop.ImageCropTask;
import net.imagine.core.crop.ImageCropTemplate;
import net.imagine.provider.fastdfs.FastDFSFileOperator;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

public class ImageCutter extends ImageCropTemplate {
	private static final Log logger = LogFactory.getLog(ImageCutter.class);
	private FileKeyGenerator fileKeyGen = new SimpleFileKeyGenerator();
	private FastDFSFileOperator fileOperator = null;

	@Override
	protected File generateLocalFile(String basePath, ImageCropTask task, List<String> localFileList) {
		SkylineImageCropTask cropTask = (SkylineImageCropTask) task;
		String remoteFileKey = cropTask.getRemoteFileKey();
		if (fileOperator != null) {
			Long albumId = cropTask.getAlbumId();
			Long userId = cropTask.getUserId();
			String filename = cropTask.getFilename();
			String filePath = SkylineImagineUtils.generateFilePath(basePath, userId, albumId, filename);
			File localFile = generateFile(filePath); //下载前需要创建相关路径
			try {
				fileOperator.downloadFile(remoteFileKey, filePath);
			} catch (Exception e) {
				logger.warn("下载图片失败", e);
				return null;
			}
			localFileList.add(filePath);
//			File localFile = new File(filePath);
			cropTask.setLocalStorePath(filePath);
			cropTask.setFileSize(localFile.length());
			return localFile;
		} else {
			String filePath = basePath + "/" + remoteFileKey;
			File localFile = new File(filePath);
			if (localFile.exists()) {
				cropTask.setLocalStorePath(filePath);
				cropTask.setFileSize(localFile.length());
				return localFile;
			} else {
				return null;
				// Long albumId = cropTask.getAlbumId();
				// Long userId = cropTask.getUserId();
				// String filename = FilenameUtils.getName(remoteFileKey);
				// filePath = SkylineImagineUtils.generateFilePath(basePath,
				// userId, albumId, filename);
				// localFile = generateFile(filePath);
				// try {
				// FileOutputStream out = FileUtils.openOutputStream(localFile);
				// InputStream in = task.getInputStream();
				// IOUtils.copy(in, out);
				// SkylineImagineUtils.closeStream(in);
				// SkylineImagineUtils.closeStream(out);
				// localFileList.add(filePath);
				// return localFile;
				// } catch (Exception e) {
				// logger.warn("下载图片失败", e);
				// return null;
				// }
			}
		}
	}

	@Override
	protected File generateDestFile(String basePath, ImageCropTask task, String ext) {
		SkylineImageCropTask cropTask = (SkylineImageCropTask) task;
		Long albumId = cropTask.getAlbumId();
		Long userId = cropTask.getUserId();
		String filename = cropTask.getFilename();
		if (!StringUtils.hasLength(ext)) {
			ext = SkylineImagineUtils.DEFAULT_EXT;
		}

		String fileKey = fileKeyGen.generateFileKey(userId.toString(), albumId.toString(), filename);
		String destFilename = fileKey + "." + ext;
		String filePath = SkylineImagineUtils.generateFilePath(basePath, userId, albumId, destFilename);
		
		return generateFile(filePath);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected ImageCropResult processResult(ResultState state, ImageCropTask task, String[] fileKeys, ImageInfo info) {
		ImageCropResult result = new ImageCropResult(state);
		SkylineImageCropTask cropTask = (SkylineImageCropTask) task;
		result.setOriginalFilename(task.getFilename());
		// 处理最终的结果
		if (state == ResultState.SUCCESS) {
			if (info == null) { // 没有做解析过的压缩必然有问题，特殊处理下
				result.setResultState(ResultState.NOT_IMAGE);
				return result;
			}
			result.setFileSize(cropTask.getFileSize());
			long userId = cropTask.getUserId();
			long albumId = cropTask.getAlbumId();
			// fileKey带上路径，方便页面生成
			result.setFileKey(fileKeys[0]);
			result.setUserId(userId);
			result.setAlbumId(albumId);
			String ext = info.getExt();
			result.setExt(ext);
		}
		return result;
	}

	@Override
	protected ResultState storeCroppedFile(String destFile, String[] fileKeys, ImageCropTask task, List<String> localFileList) {
		/*
		 * if local just return SUCCESS, if NFS need to copy localFile to NFS
		 * server, we may change to use fastdfs in the future
		 */
		if (fileOperator == null) {
			SkylineImageCropTask resizeTask = (SkylineImageCropTask) task;
			long userId = resizeTask.getUserId();
			long albumId = resizeTask.getAlbumId();
			String path = SkylineImagineUtils.generateFilePath("", userId, albumId);
			String filename = FilenameUtils.getName(destFile);
			fileKeys[0] = path + filename;
			return ResultState.SUCCESS;
		} else {
			try {
				String[] result = fileOperator.uploadFile(new File(destFile));
				// String groupName = result[0];
				String remoutKey = result[1];
				fileKeys[0] = FilenameUtils.removeExtension(remoutKey);
				localFileList.add(destFile);
				return ResultState.SUCCESS;
			} catch (Exception e) {
				logger.warn("上传文件到DFS失败", e);
				return ResultState.STORE_FAILED;
			}
		}
	}
	
	@Override
	protected void deleteFiles(List<String> localFileList) {
		for(String file : localFileList) {
			try {
				FileUtils.forceDelete(new File(file));
			} catch (IOException e) {
				logger.warn("delete file failed", e);
			}			
		}	
	}
	
	public void setFileOperator(FastDFSFileOperator fileOperator) {
		this.fileOperator = fileOperator;
	}
}
